package com.woniuxy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.controller.info.UserInfo;
import com.woniuxy.dao.ProjectUrlDao;
import com.woniuxy.utils.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class SuccessHandler implements AuthenticationSuccessHandler {

    private ObjectMapper objectMapper=new ObjectMapper();

    private ProjectUrlDao projectUrlDao;

    public SuccessHandler(){

    }
    public SuccessHandler(ProjectUrlDao projectUrlDao){
        this.projectUrlDao=projectUrlDao;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //Object principal = authentication.getPrincipal();
        UserInfo userInfo = (UserInfo) authentication.getPrincipal();
        Result result= Result.success(200,"登录成功",userInfo.getId());


        List<String> url = projectUrlDao.getUrlByAccountId(userInfo.getId());
        for (String s : url) {
            System.out.println(s);
        }
        request.getSession().setAttribute("urls",url);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}
